package com.lz.ccjdemo.view;

import android.content.Context;
import android.support.v4.view.NestedScrollingChild;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewParent;
import android.webkit.WebView;
import android.widget.ScrollView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**********************************************************************
 * @desc webView 嵌套滚动事件处理
 * @author lz
 * @data 2024/3/12 or 14:53
 *====================================================================*/
public class NestedScrollWebView extends WebView implements NestedScrollingChild {
    //最大递归深度，避免异常，防止嵌套层级导致判断无效
    int MAX_PARENT_DEPTH = 3;


    public NestedScrollWebView(@NonNull Context context) {
        super(context);
    }

    public NestedScrollWebView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public NestedScrollWebView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public NestedScrollWebView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            ViewParent viewParent = findViewParentIfNeeds(this, MAX_PARENT_DEPTH);
            if(viewParent != null){
                // 父组件不要拦截
                viewParent.requestDisallowInterceptTouchEvent(true);
            }
        }
        return super.onTouchEvent(event);
    }

    private ViewParent findViewParentIfNeeds(View tag, int depth){

        if (depth < 0) {
            return null;
        }

        ViewParent parent = tag.getParent();
        if (parent == null) {
            return null;
        }

        if (parent instanceof ScrollView || parent instanceof ViewPager){
            return parent;
        }
        return findViewParentIfNeeds((View) parent, depth - 1);
    }


    @Override
    protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY){
        if (clampedX || clampedY) {
            ViewParent viewParent = findViewParentIfNeeds(this, MAX_PARENT_DEPTH);
            if (viewParent != null) {
                // 父组件可以根据自身判断来决定是否拦截
                viewParent.requestDisallowInterceptTouchEvent(false);
            }
        }

        super.onOverScrolled(scrollX, scrollY, clampedX, clampedY);
    }
}
